<?php
declare(strict_types=1);

namespace app\result;
//验证码逻辑
use app\model\CodeLog;
use app\model\user\User;

class CodeResult extends BaseResult
{
    public function __construct()
    {
        $this->model = new CodeLog();
        parent::__construct();
    }

    /**
     * 发送验证码
     * @param $account
     * @return array
     */
    public function send_code($account, $type = 1)
    {
        if (empty($account)) {
            return $this->error_return('邮箱不能为空');
        }

        if (!filter_var($account, FILTER_VALIDATE_EMAIL)) {
            return $this->error_return('邮箱格式不正确');
        }


        $code = rand(100000, 999999);
        //1分钟内不能重复发送
        $time = time() - 60;
        $where = [
            ['account', '=', $account],
            ['status', '=', 0],
            ['created_at', '>', date('Y-m-d H:i:s', $time)],
        ];
        if ($this->model->data_count($where)) {
            return $this->error_return('发送频繁，请稍后再试');
        }

        $send = (new EmailResult())->send_code([
            'email' => $account,
            'title' => '验证码',
            'content' => "<div style='font-family: Arial, sans-serif;'>
    <p>尊敬的用户，您的验证码为：<span style='font-weight:bold;'>" . $code . "</span>。本验证码5分钟内有效，请勿泄露给他人。</p>
</div>",
            'sub_title' => '验证码, 5分钟内有效'
        ]);
        if ($send['code'] <> 0) {
            return self::error_return('发送失败', $send['msg']);
        }

        $res = (new CodeLog())->data_add(['account' => $account, 'code' => $code, 'type' => $type]);
        if (!$res) {
            return $this->error_return('发送失败');
        }
        return $this->success_return('发送成功');
    }

    //验证验证码
    public function check_code($account, $code, $type = '')
    {
        if (empty($account)) {
            return $this->error_return('邮箱不能为空');
        }
        if (empty($code)) {
            return $this->error_return('验证码不能为空');
        }
        $where = [
            ['account', '=', $account],
            ['code', '=', $code],
            ['status', '=', 0],
        ];
        if ($type) {
            $where[] = ['type', '=', $type];
        }
        $res = $this->model->data_get($where);
        if (!$res) {
            return $this->error_return('验证码错误');
        }
        //5分钟有效
        if (time() - strtotime($res['created_at']) > 300) {
            return $this->error_return('验证码已过期');
        }
        //更新状态
        $this->model->data_update($where, ['status' => 1]);

        return $this->success_return('验证成功');
    }

    //生成验证码
    public function captcha_create(): array
    {
        $rs = captcha();
        $base64_image = "data:image/png;base64," . base64_encode($rs->getData());
        $key = session('captcha.key');
        cache($key, $key, config('captcha.expire'));
        return $this->success_return('success', [
            'captcha' => [
                'img' => $base64_image,
                'key' => $key,
            ]
        ]);
    }

    //验证图形验证码
    public function captcha_check($key, $code): bool
    {
        if (!$key = cache($key)) {
            return false;
        }
        $code = mb_strtolower($code, 'UTF-8');

        $res = password_verify($code, $key);

        if ($res) {
            cache($key, null);
        }

        return $res;
    }

    public function list($args)
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $type = trim($args['type'] ?? '');
        $where = [];
        if (!empty($args['keyword'])) {
            $where[] = ['account', 'like', '%' . trim($args['keyword']) . '%'];
        }
        if (is_numeric($type)) {
            $where[] = ['type', '=', $type];
        }

        $total = $this->model->data_count($where);
        $data = $this->model->data_list($where, '*', 'id desc', $page, $pageSize);
        if ($data) {
            foreach ($data as &$item) {
                $item['status_text'] = $item['status'] == 0 ? '未验证' : '已验证';
            }
            unset($item);
        }
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data
        ]);
    }
}
